package cn.anquing.util;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CookieUtil {

	/**
	 * 
	 * @param response
	 * @param cookieName
	 * @param cookieValue
	 * @param cookieMaxage 如果传的是null，那么就默认时间（默认时间是该cookie直到浏览器关闭就过期）
	 */
	public final static void setCookie(HttpServletResponse response,
			String cookieName, String cookieValue, Integer cookieMaxage) {
		Cookie cookie = new Cookie(cookieName, cookieValue);
		//如果传的是null，那么就默认时间（默认时间是该cookie直到浏览器关闭就过期）
		if(cookieMaxage!=null){
			cookie.setMaxAge(cookieMaxage);
		}
		cookie.setPath("/");
		response.setCharacterEncoding("utf-8");
		System.out.println("addCookie----------------");
		response.addCookie(cookie);
	}

	public static  String getCookieValue(HttpServletRequest request, String cookieName) {
		Cookie cookieList[] = request.getCookies();
		if (cookieList == null || cookieName == null)
			return null;
		String retValue = null;
			for (int i = 0; i < cookieList.length; i++) {
				if (cookieList[i].getName().equals(cookieName)) {
					retValue = cookieList[i].getValue();
					break;
				}
			}
		return retValue;
	}
}
